package com.api.test;

import java.util.HashMap;
import java.util.Map;

import com.api.client.model.ApiLoginHandler;
import com.api.client.model.ApiProxyFactory;

public class ApiScribeImpl implements Api {

	private ApiProxyFactory apiFactory;

	private ApiLoginHandler loginHandler;

	private Map<Class<?>, Object> services = new HashMap<Class<?>, Object>();

	public ApiScribeImpl(ApiLoginHandler loginHandler, ApiProxyFactory apiFactory) {

		if (loginHandler == null || apiFactory == null) {

			throw new IllegalArgumentException("LoginHandler and ApiFactory cannot be null");
		}

		this.apiFactory = apiFactory;
		this.loginHandler = loginHandler;
	}

	@Override
	public void login(String username, String password) {

		loginHandler.login(username, password);
	}

	public void setAccess(String accessKey, String accessSecret) {

		loginHandler.setAccessKeys(accessKey, accessSecret);
	}

	@Override
	public <T> T getService(Class<T> serviceClass) {

		return lazyInitService(serviceClass);
	}

	@Override
	public String getAccessKey() {

		if (loginHandler.isLoggedIn()) {

			return loginHandler.getAccessKey();
		} else {
			throw new IllegalStateException("User is not logged in");
		}
	}

	public <T> T lazyInitService(Class<T> serviceClass) {

		T service = null;

		if (services.containsKey(serviceClass)) {

			@SuppressWarnings("unchecked")
			T apiService = (T) services.get(serviceClass);
			service = apiService;
		} else {
			service = apiFactory.getProxy(serviceClass);
			services.put(serviceClass, service);
		}
		return service;
	}

}
